<?php

namespace App\Models\Api;

use App\Traits\ChatBase;
use Illuminate\Database\Eloquent\Model;
use mysql_xdevapi\Exception;

/**
 * \App\Models\Api\User
 *
 * @property int $id
 * @property string $user_name  用户名
 * @property string $password  密码
 * @property string|null $last_login_token 上次登录token
 * @property int $status 状态
 * @property \Illuminate\Support\Carbon $created_at
 * @property \Illuminate\Support\Carbon $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|User newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|User newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|User query()
 * @method static \Illuminate\Database\Eloquent\Builder|User whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereLastLoginToken($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User wherePassword($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereUserName($value)
 * @mixin \Eloquent
 */
class User extends Model
{
    protected $fillable = ['user_name', 'password', 'last_login_token', 'status'/*, 'created_at', 'updated_at'*/];

    const STATUS_ON = 1;
    const STATUS_OFF = 2;
    public static $status = [
        self::STATUS_ON => '启用',
        self::STATUS_OFF => '禁用'
    ];

    use ChatBase;

    /**
     * 生成用户登录token
     * @param $userInfo
     * @return string
     */
    public static function setToken($userInfo): string
    {
        if(!empty($userInfo->last_login_token)) {
            (new User)->delUser($userInfo->last_login_token);
        }
        $token = md5($userInfo['id'] . $userInfo['user_name'] . $userInfo['password'] . time());

        $userInfo->last_login_token = $token;
        if(false === $userInfo->save()) {
            throw new Exception('更新用户 token 失败');
        }

        (new User)->setUser($token, $userInfo);

        return $token;
    }

    public function friends(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(Friend::class, 'uid', 'id');
    }

    public function getUserById($uid)
    {
        return self::whereId($uid)->whereStatus(User::STATUS_ON)->first();
    }
}
